package com.example.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.example.demo.util.RedisUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Goods;
import com.example.demo.exception.ApplicationException;
import com.example.demo.service.GoodsService;
import com.example.demo.mapper.GoodsMapper;
import com.example.demo.util.StringUtil;
import com.example.demo.vo.Result;
import com.example.demo.vo.ResultCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @author 15085202591
* @description 针对表【goods】的数据库操作Service实现
* @createDate 2024-05-31 21:14:59
*/
@Slf4j
@Service

public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService{

    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public void addGoods(Goods goods) {
        // 调用mapper
        int row = goodsMapper.insert(goods);
        if (row != 1) {
            log.warn("服务错误");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A9999));
        }

        log.info("商品插入成功");
    }

    @Override
    public String getDescriptionById(Long id) {
        // 1. 校验参数
        if (id < 1) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 调用mapper
        Goods goods = goodsMapper.selectById(id);

        // 3. 成功返回
        log.info("查询成功");
        return goods.getDescription();
    }

    @Override
    public Goods getGoodsById(Long id) {
        // 1. 校验参数
        if (id < 0) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 调用mapper
        Goods goods = goodsMapper.selectById(id);

        // 3. 返回结果
        log.info("查询成功!");
        return goods;
    }


    @Override
    public List<Goods> getAllGoodsInfo() {

        //查询redis->有就直接返回
        // 从 Redis 中获取存储的 JSON 字符串
        String goods1 =  redisTemplate.opsForValue().get("goods");

        System.out.println(goods1);
        if(StrUtil.isNotBlank(goods1)){
            //调用工具类RedisUtil的goodsList方法，将JSON 字符串解析成list<Goods>并返回
            List<Goods> goodsList = redisUtil.getList(goods1, Goods.class);
            System.out.println(goodsList);
           return goodsList;
        }

        // 调用mapper
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        System.out.println("执行了SQL");
        wrapper.orderByDesc("pay_count");

        List<Goods> list = goodsMapper.selectList(wrapper);
        // 对每个商品的描述进行长度限制
        for (Goods goods : list) {
            goods.setDescription(truncateDescription(goods.getDescription(), 24));
            if (goods.getDiscountedPrice() == 0) {
                goods.setDiscountedPrice(goods.getPrice() * 0.9);
            }

        }
        //调用工具类RedisUtil的setList方法，将list<Goods>存入redis
        redisUtil.setList(list,"goods");

        // 成功返回
        return list;
    }

    private String truncateDescription(String description, int maxLength) {
        return description.length() <= maxLength ? description : description.substring(0, maxLength);
    }

    @Override
    public List<Goods> getGoodsByType(String type) {
        // 校验字符串参数
        if (StringUtil.isEmpty(type)) {
            log.warn("参数不能为空");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 调用mapper
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("type", type);
        List<Goods> list = goodsMapper.selectList(wrapper);

        // 对每个商品的描述进行长度限制
        for (Goods goods : list) {
            goods.setDescription(truncateDescription(goods.getDescription(), 24));
        }

        // 成功返回
        log.info("查询成功");
        return list;
    }

    @Override
    public List<Goods> getGoodsInPriceRange(Long minPrice, Long maxPrice, String goodsType) {
        // 校验参数
        if (minPrice < 0 || maxPrice < 0 || minPrice > maxPrice) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 根据参数分别进行处理
        if (goodsType != null && !goodsType.isEmpty() ) {
            // 调用mapper
            QueryWrapper<Goods> wrapper = new QueryWrapper<>();
            wrapper.between("discounted_price", minPrice, maxPrice)
                    .orderByAsc("discounted_price")
                    .eq("type", goodsType);
            List<Goods> list = goodsMapper.selectList(wrapper);

            // 对每个商品的描述进行长度限制
            for (Goods goods : list) {
                goods.setDescription(truncateDescription(goods.getDescription(), 24));
            }
            // 成功返回
            log.info("查询成功");
            return list;
        }

        // 调用mapper
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.between("discounted_price", minPrice, maxPrice).orderByAsc("discounted_price");
        List<Goods> list = goodsMapper.selectList(wrapper);

        // 对每个商品的描述进行长度限制
        for (Goods goods : list) {
            goods.setDescription(truncateDescription(goods.getDescription(), 24));
        }
        // 成功返回
        log.info("查询成功");
        return list;
    }

    @Override
    public List<Goods> getGoodsOrderByPriceDesc() {
        // 调用mapper
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("discounted_price");
        List<Goods> list = goodsMapper.selectList(wrapper);

        // 对每个商品的描述进行长度限制
        for (Goods goods : list) {
            goods.setDescription(truncateDescription(goods.getDescription(), 24));
        }

        // 成功返回
        log.info("查询成功");
        return list;
    }

    @Override
    public List<Goods> getGoodsOrderByPriceAsc() {
        // 调用mapper
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("discounted_price");
        List<Goods> list = goodsMapper.selectList(wrapper);

        // 对每个商品的描述进行长度限制
        for (Goods goods : list) {
            goods.setDescription(truncateDescription(goods.getDescription(), 24));
        }

        // 成功返回
        log.info("查询成功");
        return list;
    }

    @Override
    public void deleteGoodsById(Long id) {
        // 1. 参数校验
        if (id == null || id < 1) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 调用mapper
        int row = goodsMapper.deleteById(id);
        if (row != 1) {
            log.warn("删除失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A9999));
        }

        log.info("删除成功");
    }

    @Override
    public List<Goods> getGoodsByName(String goodsName, Integer index) {
        // 1. 校验参数
        if (StringUtil.isEmpty(goodsName)) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 调用mapper
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        if (index == 0) {
            wrapper.like("goods_name", goodsName).orderByDesc("pay_count");
        }
        if (index == 1) {
            wrapper.like("goods_name", goodsName).orderByDesc("price");
        }
        if (index == 2) {
            wrapper.like("goods_name", goodsName).orderByAsc("price");
        }

        List<Goods> list = goodsMapper.selectList(wrapper);

        // 对每个商品的描述进行长度限制
        for (Goods goods : list) {
            goods.setDescription(truncateDescription(goods.getDescription(), 24));
        }

        // 3. 返回
        log.info("查询成功!");
        return list;
    }

    @Override
    public List<Goods> getGoodsByNameWithBId(String goodsName, Integer index, Long bid) {
        // 1. 校验参数
        if (StringUtil.isEmpty(goodsName)) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 调用mapper
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        if (index == 0) {
            wrapper.like("goods_name", goodsName).orderByDesc("pay_count").eq("business_id", bid);
        }
        if (index == 1) {
            wrapper.like("goods_name", goodsName).orderByDesc("price").eq("business_id", bid);
        }
        if (index == 2) {
            wrapper.like("goods_name", goodsName).orderByAsc("price").eq("business_id", bid);
        }

        List<Goods> list = goodsMapper.selectList(wrapper);

        // 对每个商品的描述进行长度限制
        for (Goods goods : list) {
            goods.setDescription(truncateDescription(goods.getDescription(), 24));
        }

        // 3. 返回
        log.info("查询成功!");
        return list;
    }

    @Override
    public List<Goods> getGoodsByBusinessId(Long businessId) {
        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("business_id",businessId);
        List<Goods> list = goodsMapper.selectByMap(columnMap);
        return list;
    }

    @Override
    public Integer reduceGoodsByGoodsId(Long goodsId, Long number) {
        // 1. 校验参数
        if (goodsId < 1 || number < 0) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 构造新对象
        Goods goods = goodsMapper.selectById(goodsId);
        if (goods == null) {
            log.warn("商品状态异常");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0013));
        }
        if (goods.getNumber() < number) {
            log.warn("库存不足");
            return 0;

        }
        goods.setPayCount(goods.getPayCount() + number);
        goods.setNumber(goods.getNumber() - number);
        goods.setUpdateTime(LocalDateTime.now());

        // 3. 调用mapper
        int row = goodsMapper.updateById(goods);
        if (row != 1) {
            log.warn("服务错误");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A9999));
        }

        log.info("修改成功");
        return 1;
    }

    @Override
    public void updateGood(Goods good) {
        good.setUpdateTime(LocalDateTime.now());
        goodsMapper.updateGood(good);
    }

}




